﻿using System;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;

using AD.Pms.Core;
using AD.Pms.Core.Jwt;
using AD.Pms.Core.ClientApi;
using AD.Pms.Core.EnumHelper;
using AD.Pms.Service.Request;
using AD.Pms.Core.ConfigHelper;
using AD.Pms.Service.Interfaces;

namespace AD.Pms.Api.Controllers.V1
{
    /// <summary>
    /// 
    /// </summary>
    [Route("api/v1/[controller]/[action]")]
    [ApiController]
    public class OauthController : ControllerBase
    {
        #region DI
        private readonly ILogger _logger;
        private readonly ILoginService _logService;
        public OauthController(ILogger<OauthController> logger, ILoginService loginService)
        {
            _logger = logger;
            _logService = loginService;
        }
        #endregion

        /// <summary>
        /// 模拟登录，获取JWT
        /// </summary>
        /// <param name="tm"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetJwt()
        {
            var tm = new TokenModel()
            {
                Uid = Guid.NewGuid().ToString(),
                UserName = "User",
                Role = "Admin"
            };
            return Ok(JwtHelper.IssueJWT(tm));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpGet]
        public ApiResult<string> Auth(string phone, string code)
        {
            var apiRes = new ApiResult<string>();
            var token = "";
            try
            {
                // 查询登录结果
                var dbres = _logService.LoginAsync(new LoginRequest { Phone = phone, code = code }).Result;

                if (dbres.statusCode != 200)
                {

                    return apiRes;
                }

                var user = dbres.data.admin;
                var identity = new ClaimsPrincipal(new ClaimsIdentity(new[] {
                    new Claim(ClaimTypes.Sid,user.UserID.ToString()),
                    //new Claim(ClaimTypes.Role,user.),
                    //new Claim(ClaimTypes.Thumbprint,user.HeadPic),
                    new Claim(ClaimTypes.Name,user.Phone),
                    new Claim(ClaimTypes.WindowsAccountName,user.Phone),
                    new Claim(ClaimTypes.UserData,user.LastLoginTime.ToString())
                }, CookieAuthenticationDefaults.AuthenticationScheme));

                //根据配置保存浏览器用户信息，小时单位
                var hours = int.Parse(ConfigExtensions.Configuration[KeyHelper.LOGINCOOKIEEXPIRES]);
                HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identity, new AuthenticationProperties
                {
                    ExpiresUtc = DateTime.UtcNow.AddHours(hours),
                    IsPersistent = true,
                    AllowRefresh = false
                });

                token = JwtHelper.IssueJWT(new TokenModel()
                {
                    Uid = user.UserID.ToString(),
                    UserName = user.Phone,
                    Role = "Admin"
                });
            }
            catch (Exception ex)
            {
                apiRes.message = ex.Message;
                apiRes.statusCode = (int)ApiEnum.Error;
                _logger.LogError($"用户登录授权异常.{ex.Message}", ex);
            }
            apiRes.data = token;

            return apiRes;
        }
    }
}